from django.shortcuts import render

# Create your views here.
from axfMarket.models import Axf_foodtype, AxfGoods
from axfMarket.view_constant import COMP_SORT, ORDER_BY_PRICE_UP, ORDER_BY_PRICE_DOWN, ORDER_BY_PRODUCTNUM_UP, \
    ORDER_BY_PRODUCTNUM_DOWN


def market(request):
    # 左边
    axfoodtypes = Axf_foodtype.objects.all()

    # 右上
    typeid = request.GET.get('typeid', '104749')

    childtypenames = Axf_foodtype.objects.filter(typeid=typeid)[0].childtypenames
    # 全部分类: 0  # 酸奶乳酸菌:103537#牛奶豆浆:103538#面包蛋糕:103540
    childtypenames_list = childtypenames.split('#')

    c_list = []
    for i in childtypenames_list:
        c = i.split(':')
        c_list.append(c)

        # 二级联动，商品数据展示，全部分类
        # axfoodtypes.typyid = axfgoods.categoryid
    goods_list = AxfGoods.objects.filter(categoryid=typeid)
    childcid = request.GET.get('childcid', '0')
    if childcid == '0':
        goods_list = goods_list
    else:
        goods_list = goods_list.filter(childcid=childcid)

    # 排序分类展示
    sort_rule_list = [
        ['全部排序', COMP_SORT],
        ['价格升序', ORDER_BY_PRICE_UP],
        ['价格降序', ORDER_BY_PRICE_DOWN],
        ['销量升序', ORDER_BY_PRODUCTNUM_UP],
        ['销量降序', ORDER_BY_PRODUCTNUM_DOWN],
    ]
    s_rule = request.GET.get('s_rule', COMP_SORT)
    if s_rule == COMP_SORT:
        pass
    elif s_rule == ORDER_BY_PRICE_UP:
        goods_list = goods_list.order_by('price')
    elif s_rule == ORDER_BY_PRICE_DOWN:
        goods_list = goods_list.order_by('-price')
    elif s_rule == ORDER_BY_PRODUCTNUM_UP:
        goods_list = goods_list.order_by('productnum')
    else:
        goods_list = goods_list.order_by('-productnum')

    context = {
        'axfoodtypes': axfoodtypes,
        'typeid': typeid,
        'good_list': goods_list,
        'c_list': c_list,
        'childcid': childcid,
        's_rule': s_rule,
        'sort_rule_list': sort_rule_list,

    }
    return render(request, 'axf/main/market/market.html', context=context)
